<script setup lang="ts">
import { dictionaryApi } from "@/api/admin/dictionary";
import { ElForm, ElFormItem, ElInput, ElDialog, ElButton, ElMessage } from "element-plus";
import { nextTick, ref } from "vue";

const isEditor = ref(false);
const visible = ref(false);

class DictionaryForm {
  id = undefined;
  name: string = "";
  code: string = "";
  remark: string = "";
}

const dictionaryForm = ref(new DictionaryForm());
const dictionaryFormRef = ref<any>(null);

const emit = defineEmits(["update"]);

// 打开弹窗
const open = (data: any = null) => {
  visible.value = true;
  if (data) {
    // console.log(data);
    isEditor.value = true;
    nextTick(() => {
      dictionaryForm.value = data;
    });
  } else {
    dictionaryForm.value = new DictionaryForm();
    isEditor.value = false;
  }
};

// 清除表单值
const clearForm = () => {
  dictionaryFormRef.value.resetFields();
};

const handleCancel = () => {
  clearForm();
  visible.value = false;
};

// 关闭弹窗
const handleClose = (deno: () => void) => {
  clearForm();
  deno();
};

const handleOk = async () => {
  await dictionaryFormRef.value.validate();
  // console.log(dictionaryForm.value);
  let ret = null;
  if (!isEditor.value) {
    ret = await dictionaryApi.saveDictionaryApi(dictionaryForm.value);
  } else {
    ret = await dictionaryApi.updateDictionaryApi(dictionaryForm.value);
  }
  if (ret.code === 200) {
    handleCancel();
    ElMessage.success(ret.msg);
    emit("update");
  } else {
    ElMessage.error(ret.data.msg);
  }
};

// 暴露方法
defineExpose({
  open,
});
</script>

<template>
  <el-dialog
    :title="isEditor ? '修改' : '新增'"
    :before-close="handleClose"
    v-model="visible"
  >
    <el-form
      ref="dictionaryFormRef"
      :model="dictionaryForm"
      label-position="right"
      label-width="70px"
    >
      <el-form-item
        prop="name"
        label="字典名称"
        :rules="[{ required: true, message: '请输入字典名称' }]"
      >
        <el-input v-model="dictionaryForm.name" placeholder="请输入字典名称" />
      </el-form-item>
      <el-form-item
        prop="code"
        label="字典编码"
        :rules="[{ required: true, message: '请输入字典编码' }]"
      >
        <el-input v-model="dictionaryForm.code" placeholder="请输入字典编码" />
      </el-form-item>
      <el-form-item prop="remark" label="字典描述">
        <el-input v-model="dictionaryForm.remark" placeholder="请输入字典描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">
          {{ isEditor ? "提交修改" : "添加" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped></style>
